#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证分类数据是否正确导入
"""

import sqlite3
import json
import os

def get_db_path():
    """获取数据库路径"""
    current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    db_path = os.path.join(current_dir, "..", "flux_prompt_helper", "promptManager-server", "instance", "prompt_manager.db")
    return db_path

def verify_categories():
    """验证分类数据"""
    db_path = get_db_path()
    
    if not os.path.exists(db_path):
        print(f"数据库文件不存在: {db_path}")
        return False
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    try:
        # 检查表是否存在
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='categories'")
        if not cursor.fetchone():
            print("categories表不存在")
            return False
        
        # 统计数据
        cursor.execute("SELECT COUNT(*) FROM categories")
        total_count = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM categories WHERE level = 0")
        main_count = cursor.fetchone()[0]
        
        cursor.execute("SELECT COUNT(*) FROM categories WHERE level > 0")
        sub_count = cursor.fetchone()[0]
        
        print(f"数据库验证结果:")
        print(f"总计: {total_count} 个分类")
        print(f"主分类: {main_count} 个")
        print(f"子分类: {sub_count} 个")
        
        # 显示主分类
        cursor.execute("SELECT category_key, category_name, description FROM categories WHERE level = 0 ORDER BY category_key")
        main_categories = cursor.fetchall()
        
        print(f"\n主分类列表:")
        for category_key, name, description in main_categories:
            print(f"  {category_key}: {name} - {description}")
        
        # 显示子分类
        cursor.execute("""
            SELECT c.category_key, c.category_name, c.description, p.category_name as parent_name
            FROM categories c
            LEFT JOIN categories p ON c.parent_id = p.id
            WHERE c.level > 0
            ORDER BY p.category_key, c.category_key
        """)
        sub_categories = cursor.fetchall()
        
        print(f"\n子分类列表:")
        current_parent = None
        for category_key, name, description, parent_name in sub_categories:
            if parent_name != current_parent:
                print(f"  {parent_name}:")
                current_parent = parent_name
            print(f"    {category_key}: {name} - {description}")
        
        # 统计每个主分类下的子分类数量
        cursor.execute("""
            SELECT p.category_name, COUNT(c.id) as sub_count
            FROM categories p
            LEFT JOIN categories c ON p.id = c.parent_id
            WHERE p.level = 0
            GROUP BY p.id, p.category_name
            ORDER BY p.category_key
        """)
        sub_counts = cursor.fetchall()
        
        print(f"\n各主分类下的子分类数量:")
        for parent_name, sub_count in sub_counts:
            print(f"  {parent_name}: {sub_count} 个子分类")
        
        return True
        
    except Exception as e:
        print(f"验证失败: {e}")
        return False
    finally:
        conn.close()

def main():
    """主函数"""
    print("开始验证分类数据")
    print("=" * 50)
    
    success = verify_categories()
    
    if success:
        print("\n分类数据验证成功!")
    else:
        print("\n分类数据验证失败!")

if __name__ == "__main__":
    main()
